<!-- eslint-disable vue/valid-v-slot -->
<!-- eslint-disable vue/no-lone-template -->
<template>
  <div class="main-container">
    <TableBody>
      <template #header>
        <TableHeader ref="tableHeaderRef" :show-filter="false">
          <template #search-content>
            <a-form ref="seachForm" :model="form">
              <a-row :gutter="24">
                <a-col :span="4">
                  <a-form-item field="name" hide-label>
                    <a-input
                      v-model="form.name"
                      class="width100"
                      placeholder="请输入套餐名称"
                      allow-clear
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="4">
                  <a-form-item field="seriesId" hide-label>
                    <a-select
                      class="width100"
                      v-model="form.seriesId"
                      placeholder="请选择系列"
                      allow-clear
                      allow-search
                    >
                      <a-option v-for="item in seriesNo" :key="item.id" :value="item.id">{{
                        item.showName
                      }}</a-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="4">
                  <a-form-item field="operator" hide-label>
                    <a-select
                      class="width100"
                      v-model="form.operator"
                      placeholder="请选择运营商"
                      allow-clear
                    >
                      <a-option :value="0">中国移动</a-option>
                      <a-option :value="1">中国联通</a-option>
                      <a-option :value="2">中国电信</a-option>
                      <a-option :value="3">中国广电</a-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="4">
                  <a-form-item field="type" hide-label>
                    <a-select
                      class="width100"
                      v-model="form.type"
                      placeholder="请选择套餐类型"
                      allow-clear
                    >
                      <a-option :value="0">无限叠加</a-option>
                      <a-option :value="1">基础套餐</a-option>
                      <a-option :value="2">叠加包</a-option>
                      <!-- <a-option :value="3">体验包</a-option> -->
                    </a-select>
                  </a-form-item>
                </a-col>

                <a-col :span="4">
                  <a-form-item field="close" hide-label>
                    <a-select
                      class="width100"
                      v-model="form.close"
                      placeholder="请选择套餐状态"
                      allow-clear
                    >
                      <a-option :value="1">关闭</a-option>
                      <a-option :value="0">开启</a-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="4">
                  <a-form-item field="btns" hide-label>
                    <a-space :size="15">
                      <a-button type="primary" html-type="submit" @click="doRefresh(1)"
                        ><template #icon>
                          <icon-search />
                        </template>
                        <!-- Use the default slot to avoid extra spaces -->
                        <template #default>搜索</template></a-button
                      >
                      <a-button @click="resetSeach"
                        ><template #icon>
                          <icon-sync theme="outline" size="14" />
                        </template>
                        <!-- Use the default slot to avoid extra spaces -->
                        <template #default>重置</template></a-button
                      >
                    </a-space>
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
          </template>
        </TableHeader>
      </template>
      <template #table-config>
        <a-space :size="15">
          <a-button type="outline" status="warning" @click="exportChannelLists" :loading="loading">
            <!-- Use the default slot to avoid extra spaces -->
            <template #default>导出</template>
          </a-button>
        </a-space>
        <a-space :size="15">
          <TableConfig
            @update-border="onUpdateBorder"
            @update-striped="onUpdateStriped"
            @refresh="doRefresh"
          />
        </a-space>
      </template>
      <template #default>
        <a-table
          :stripe="(tables.striped as boolean)"
          :loading="tables.tableLoading"
          :data="table.dataList"
          :pagination="false"
          :column-resizable="true"
          :rowKey="rowKey"
          :columns="tableColumns.list"
          table-layout-fixed
          hide-expand-button-on-empty
          :default-expand-all-rows="true"
          :bordered="{ wrapper: true, cell: tables.bordered }"
          :scroll="{ x: 1500 }"
          :scrollbar="{ type: 'track', outerClass: '', outerStyle: '' }"
        >
          <template #columns>
            <a-table-column
              v-for="item of tableColumns.list"
              :key="item.key"
              align="left"
              :title="(item.title as string)"
              :width="item.width"
              :data-index="(item.key as string)"
              :fixed="item.fixed"
              :ellipsis="true"
              :tooltip="true"
            >
              <template v-if="item.key === 'operator'" #cell="{ record }">
                <a-space>
                  <span v-if="record.series.operator == 0">移动</span>
                  <span v-else-if="record.series.operator == 1">联通</span>
                  <span v-else-if="record.series.operator == 2">电信</span>
                </a-space>
              </template>
              <template v-else-if="item.key === 'close'" #cell="{ record }">
                <a-switch
                  v-model="record.close"
                  :checked-value="false"
                  :unchecked-value="true"
                  :disabled="record.close != undefined ? false : true"
                  @change="changeState(record)"
                >
                  <template #checked-icon>
                    <icon-check />
                  </template>
                  <template #unchecked-icon>
                    <icon-close />
                  </template>
                </a-switch>
              </template>
              <template v-if="item.key === 'flowReal'" #cell="{ record }">
                <a-space>
                  <span v-if="!record.flowVirtual && !record.flowReal">无限</span>
                  <span v-else-if="record.flowVirtual">{{
                    useCommon.numbers1(record.flowVirtual)
                  }}</span>
                  <span v-else-if="record.flowReal">{{
                    useCommon.numbers1(record.flowReal)
                  }}</span></a-space
                >
              </template>
              <template v-else-if="item.key === 'run'" #cell="{ record }">
                {{ Math.floor((record.price - record.cost) * 100) / 100 }}
              </template>
              <template v-else-if="item.key === 'next'" #cell="{ record }">
                <a-space>
                  <span v-if="record.next == true">开启</span>
                  <span v-else-if="record.next == false">关闭</span>
                </a-space>
              </template>
              <template v-else-if="item.key === 'type'" #cell="{ record }">
                <a-space>
                  <span v-if="record.type == 0">无限叠加</span>
                  <span v-else-if="record.type == 1">基础套餐</span>
                  <span v-else-if="record.type == 2">叠加包</span>
                  <!-- <span v-else-if="record.type == 3">体验包</span> -->
                </a-space>
              </template>
              <template v-else-if="item.key === 'seriesName'" #cell="{ record }">
                <div
                  v-if="record.name.length < 16"
                  style="
                    width: 177px;
                    white-space: nowrap;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    text-align: left;
                  "
                  >{{ record.series.showName }}</div
                >
                <a-tooltip v-else :content="record.series.showName">
                  <div
                    style="
                      width: 150px;
                      white-space: nowrap;
                      overflow: hidden;
                      text-overflow: ellipsis;
                      text-align: left;
                    "
                    >{{ record.series.showName }}</div
                  >
                </a-tooltip>
              </template>
              <template v-else-if="item.key === 'price'" #cell="{ record }">
                <a-input-number
                  hide-button
                  @focus="inputgetRecord(record)"
                  @blur="inputSubmit(record)"
                  :style="{ background: 'none' }"
                  style="padding-left: 0"
                  v-model="record.price"
                />
              </template>

              <template v-else-if="item.key === 'cost'" #cell="{ record }">
                {{ Math.floor(record.cost * 100) / 100 }}
              </template>

              <template v-else-if="item.key === 'validity'" #cell="{ record }">
                <a-space>
                  <span v-if="record.validity">
                    <span v-if="record.validityMore == true && record.validityType == 0">
                      30&nbsp;{{ record.validityType == 0 ? '天' : '月' }}&nbsp; x&nbsp;{{
                        record.validity
                      }}
                    </span>
                    <span v-else>
                      {{ record.validity }}&nbsp;{{ record.validityType == 0 ? '天' : '月' }}
                    </span>
                  </span>
                  <span v-else>---</span>
                </a-space>
              </template>

              <template v-if="item.key === 'realNameSystem'" #cell="{ record }">
                <a-space>
                  <a-tag v-if="record.realNameSystem == 0" color="arcoblue">短信验证</a-tag>
                  <a-tag v-else-if="record.realNameSystem == 1" color="red">国政通验证</a-tag>
                  <div v-else>---</div>
                </a-space>
              </template>
              <template v-if="item.key === 'actions'" #cell="{ record }">
                <a-space>
                  <a-button
                    size="small"
                    type="text"
                    class="butten"
                    @click="infoDepartments(record, 2)"
                  >
                    售价
                  </a-button>
                  <a-button
                    size="small"
                    class="butten"
                    type="text"
                    @click="infoDepartments(record, 1)"
                  >
                    名称
                  </a-button>
                </a-space>
              </template>
            </a-table-column>
          </template>
        </a-table>
      </template>
      <template #footer>
        <TableFooter ref="tableFooterRef" :pagination="pagination" />
      </template>
    </TableBody>
    <a-modal
      v-model:visible="modal.visible"
      width="600px"
      title-align="start"
      :mask-closable="false"
      @before-close="beforeClose"
      :title="type == 1 ? '编辑名称' : '编辑售价'"
    >
      <div style="max-height: 600px; padding-bottom: 22px">
        <a-form ref="infoRef" :model="info.info" :auto-label-width="true">
          <a-form-item
            v-if="type == 1"
            label="套餐名称"
            field="showName"
            :rules="[
              { required: true, message: '请输入套餐名称' },
              { minLength: 1, maxLength: 20, message: '长度在 1 - 20个字符' },
            ]"
            asterisk-position="end"
          >
            <a-input placeholder="请输入套餐名称" v-model.trim="info.info.showName" />
          </a-form-item>
          <a-form-item v-if="type == 2" label="套餐成本" field="cost">
            <div style="color: #3491fa">{{ info.info.cost }}元</div>
          </a-form-item>
          <a-form-item
            v-if="type == 2"
            label="套餐售价"
            field="price"
            :rules="[{ required: true, message: '请输入套餐售价' }]"
            asterisk-position="end"
          >
            <a-input-number
              placeholder="请输入套餐售价"
              v-model.trim="info.info.price"
              hide-button
            />
          </a-form-item>
          <a-form-item v-if="type == 2" label="套餐利润" field="lirun">
            <a-input-number
              placeholder="点击计算利润"
              :read-only="true"
              v-model.trim="info.info.lirun"
            >
              <template #append>
                <a-button type="text" style="height: 20px" size="mini" @click="jisuan">
                  计算利润
                </a-button>
              </template>
            </a-input-number>
          </a-form-item>
        </a-form>
      </div>
      <template #footer>
        <a-space>
          <a-button @click="beforeClose">取消</a-button>
          <a-button type="primary" @click="handleSubmit">确定</a-button>
        </a-space>
      </template>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import { getUserMealList, mealclose, mealname, mealprice, exportUserMealList } from '@/api/user'
  import useCommonStore from '@/store/modules/common'
  import { get } from '@/api/http'
  import { usePagination, useRowKey, useTable } from '@/hooks/table'
  import { onMounted, reactive, ref } from 'vue'

  import _ from 'lodash-es'

  import { Message, Modal } from '@arco-design/web-vue'

  const useCommon = useCommonStore()

  const table = useTable()
  const type = ref(1)

  const pagination = usePagination(doRefresh)

  const infoRef = ref()

  const seachForm = ref()

  const loading = ref(false)
  const seriesNo = ref()

  const modal = reactive({
    visible: false,
    visibleRealName: false,
  })

  const form = reactive({
    channelId: '', //渠道id
    seriesId: '', //系列id
    type: '', //套餐类型
    next: '', //次月
    close: '', //状态
    name: '', //系列类型
    operator: '', //运营商
    addTime: '',
    endTime: '',
  })

  const tables = reactive({
    tableLoading: false,
    bordered: false,
    striped: false,
    expand: [1],
    isExpand: false,
  })

  const info: any = reactive({
    info: {
      id: '',
      seriesId: '', //系列ID
      type: '', //套餐类型 0无限叠加 1基础套餐 2叠加包 3体验包
      name: '', //套餐名称
      showName: '', //显示名称
      validity: '', //有效期
      validityType: 1, //有效期类型 0天 1月
      validityRule: '', //有效期规则 0-月底清零 1-26号清理
      cost: '', //套餐成本
      price: '', //套餐售价
      priceMin: '', //限制代理最低售价
      priceMax: '', //限制代理最高售价
      flowReal: '', //真实流量 单位MB
      flowVirtualType: 0, //虚量方案类型 0固定流量 1动态流量
      flowVirtual: '', //虚量流量单位MB
      flowVirtualId: '', //虚量流量动态方案ID 从/app/set/meal/flow/virtual/get/name/list接口获取
      encoding: '', //套餐编码
      underline: '', //划线价格
      introduction: '',
      next: true, //次月套餐 false关闭 true开启
      postponed: true, //顺延 false关闭 true开启
      multiMonth: true, //多月到账 false关闭 true开启
      sort: '', //排序
      colour: true, //展示颜色
      leftLower: '', //左下文字
      rightUpper: '', //右上文字
      rightLower: '', //右下文字
      close: true, //状态true关闭,  false正常
    },
    disabled: false,
  })

  const tableColumns: any = reactive({
    list: [
      {
        title: '套餐编码',
        key: 'id',
        dataIndex: 'id',
        align: 'center',
        checked: true,
        width: 90,
      },
      {
        title: '套餐名称',
        key: 'showName',
        dataIndex: 'showName',
        align: 'center',
        checked: true,
        width: 177,
      },
      {
        title: '所属系列',
        key: 'seriesName',
        dataIndex: 'seriesName',
        align: 'center',
        checked: true,
        width: 177,
      },
      {
        title: '套餐类型',
        key: 'type',
        dataIndex: 'type',
        align: 'center',
        checked: true,
        width: 173,
      },
      {
        title: '套餐流量',
        key: 'flowReal',
        dataIndex: 'flowReal',
        align: 'center',
        checked: true,
        width: 145,
      },
      {
        title: '有效期',
        key: 'validity',
        dataIndex: 'validity',
        align: 'center',
        checked: true,
        width: 145,
      },
      {
        title: '套餐成本',
        key: 'cost',
        dataIndex: 'cost',
        align: 'center',
        checked: true,
        width: 145,
      },
      {
        title: '套餐售价',
        key: 'price',
        dataIndex: 'price',
        align: 'center',
        checked: true,
        width: 145,
      },
      {
        title: '套餐利润',
        key: 'run',
        dataIndex: 'run',
        align: 'center',
        checked: true,
        width: 145,
      },
      {
        title: '套餐状态',
        key: 'close',
        dataIndex: 'close',
        align: 'center',
        checked: true,
        width: 145,
      },
      {
        title: '操作',
        key: 'actions',
        dataIndex: 'actions',
        align: 'center',
        checked: true,
        fixed: 'right',
        width: 130,
      },
    ],
  })

  const rowKey = useRowKey('id')

  const inputSubmit = (val: any) => {
    get({
      url: mealprice,
      data: () => {
        return {
          setMealId: val.id,
          price: val.price,
        }
      },
    }).then((res) => {
      if (res.code == 0) {
        Message.success(res.msg)
        doRefresh()
      }
    })
  }

  const jisuan = () => {
    if (!info.info.price) {
    } else {
      info.info.lirun = Math.floor((info.info.price - info.info.cost) * 100) / 100
    }
  }

  const seriesIds = () => {
    useCommon.userseriess().then((res) => {
      seriesNo.value = res.data
    })
  }

  const resetSeach = () => {
    seachForm.value.resetFields()
    doRefresh(1)
  }

  const exportChannelLists = () => {
    loading.value = true
    useCommon
      .downLoads(exportUserMealList, form, '套餐列表')
      .then(() => {
        loading.value = false
      })
      .catch(() => {
        loading.value = false
      })
  }

  const beforeClose = () => {
    infoRef.value.resetFields()
    modal.visible = false
  }

  function changeState(item: any) {
    Modal.warning({
      title: '操作确认',
      content: '确定要改变套餐状态吗？',
      cancelText: '取消',
      titleAlign: 'start',
      hideCancel: false,
      okText: '确定',
      onOk() {
        get({
          url: mealclose,
          data: () => {
            return {
              close: item.close,
              setMealId: item.id,
            }
          },
        }).then((res) => {
          if (res.code == 0) {
            Message.success(res.msg)
            doRefresh()
          } else {
            Message.error(res.msg)
          }
        })
      },
    })
  }
  const handleSubmit = () => {
    // console.log(info.info)
    // return false
    infoRef.value.validate((error: any) => {
      if (!error) {
        if (type.value == 1) {
          updateMeals()
        } else {
          addMeals()
        }
      }
    })
  }

  const infoDepartments = async (val: any, val1: any) => {
    type.value = val1
    info.info = JSON.parse(JSON.stringify(val))
    modal.visible = true
  }

  const updateMeals = () => {
    get({
      url: mealname,
      data: () => {
        return {
          setMealId: info.info.id,
          name: info.info.name,
        }
      },
    }).then((res) => {
      if (res.code == 0) {
        Message.success(res.msg)
        beforeClose()
        doRefresh()
      }
    })
  }

  const addMeals = () => {
    get({
      url: mealprice,
      data: () => {
        return {
          setMealId: info.info.id,
          price: info.info.price,
        }
      },
    }).then((res) => {
      if (res.code == 0) {
        Message.success(res.msg)
        beforeClose()
        doRefresh()
      }
    })
  }

  function onUpdateBorder(isBordered: boolean) {
    tables.bordered = isBordered
  }

  function onUpdateStriped(isStriped: boolean) {
    tables.striped = isStriped
  }

  function doRefresh(value?: number) {
    tables.tableLoading = true
    if (value) {
      pagination.page = value
    }
    get({
      url: getUserMealList,
      data: {
        ...form,
        page: pagination.page,
        size: pagination.pageSize,
      },
    }).then((res) => {
      tables.tableLoading = false
      table.handleSuccess(res.data.list)
      pagination.setTotalSize((res.data as any).totalSize)
      return res.data.list
    })
  }

  onMounted(async () => {
    await doRefresh()
    // await getTableDepartments()
    // await channel()
    // await getxuliangs()
    await seriesIds()
    // await encodingFn()
  })
</script>

<style lang="less" scoped>
  :deep(.arco-input-append) {
    border: 0;
  }
  :deep(.arco-table-cell-expand-icon) {
    justify-content: center;
  }
  :deep(.arco-input-append) {
    padding: 0px;
  }
  .tabs {
    display: flex;
    justify-content: space-around;
    align-items: center;
    height: 40px;
    margin-bottom: 20px;

    .button {
      box-sizing: border-box;
      padding-bottom: 5px;
    }
  }
  .action {
    color: #009dff;
    border-bottom: 3px solid #009dff;
  }

  .butten {
    padding: 0px 4px;
  }
</style>
